﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;


namespace Server
{
    public partial class Server : Form
    {
        TcpListener listener;
        StreamReader reader;
        StreamWriter writer;
        private const int BUFFER_SIZE = 1024;
        private const int PORT_NUMBER = 2013;

        static ASCIIEncoding encoding = new ASCIIEncoding();

        public Server()
        {
            InitializeComponent();
            start();
        }
        public void start()
        { 
        IPAddress address = IPAddress.Parse("127.0.0.1");
          listener=new TcpListener(address,PORT_NUMBER);
            // 1. listen
            listener.Start(); 
            richTextBox2.Text="Server started on "+listener.LocalEndpoint;
            richTextBox2.Text="Waiting for a connection...";
           Socket socket=listener.AcceptSocket();
            richTextBox2.Text="Connection received from " + socket.RemoteEndPoint;
              var stream = new NetworkStream(socket);
             reader=new StreamReader(stream);
             writer=new StreamWriter(stream);
            writer.AutoFlush=true;

            while (true)
            {
                // 2. receive
                string str = reader.ReadLine();
                richTextBox2.Text = "\nClient: " + str;
                // 3. send
                writer.WriteLine("Hello " + str);
            }
            }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox2.Text != "")
                writer.WriteLine(textBox2.Text);
        }
    }
}
